package com.weixing.mall.provider.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.properties.ali.OssProperties;
import com.weixing.mall.core.support.upload.AliOssUpload;
import com.weixing.mall.provider.mapper.PhotoAlbumMapper;
import com.weixing.mall.provider.mapper.PhotoGalleryMapper;
import com.weixing.mall.provider.model.domain.PhotoAlbum;
import com.weixing.mall.provider.model.domain.PhotoGallery;
import com.weixing.mall.provider.model.dto.PhotoAlbumDto;
import com.weixing.mall.provider.model.dto.PhotoChgDto;
import com.weixing.mall.provider.model.query.PhotoAlbumQuery;
import com.weixing.mall.provider.model.query.PhotoGalleryQuery;
import com.weixing.mall.provider.model.vo.PhotoAlbumVo;
import com.weixing.mall.provider.model.vo.PhotoGalleryVo;
import com.weixing.mall.provider.service.IGoodsIntroService;
import com.weixing.mall.provider.service.IGoodsService;
import com.weixing.mall.provider.service.IPhotoAlbumService;
import com.weixing.mall.provider.service.IPhotoGalleryService;
import com.weixing.mall.provider.support.excel.PhotoAlbumData;
import com.weixing.mall.provider.support.excel.PhotoAlbumDataListener;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName PhotoAlbumServiceImpl
 * @Description TODO <br/>
 * @Author gjq
 * @Modified By:
 * @Date 2019/8/7
 * @Version 1.0
 **/

/**
 * <p>
 * 商品模块-商品图片相册表 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class PhotoAlbumServiceImpl extends ServiceImpl<PhotoAlbumMapper, PhotoAlbum> implements IPhotoAlbumService {

    @Autowired
    private PhotoGalleryMapper photoGalleryMapper;
    @Autowired
    private IPhotoGalleryService photoGalleryService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsIntroService goodsIntroService;
    @Autowired
    private WeiXingProperties weiXingProperties;

    @Override
    public void save(PhotoAlbumDto photoAlbumDto) {
        PhotoAlbum photoAlbum = new PhotoAlbum();
        BeanUtils.copyProperties(photoAlbumDto, photoAlbum);
        photoAlbum.setIsEnable(photoAlbumDto.getIsEnable().getValue());
        if (null == photoAlbumDto.getId()) {
            save(photoAlbum);
        } else {
            updateById(photoAlbum);
        }
    }

    @Override
    public IPage<PhotoAlbumVo> selectOfPage(Page page, PhotoAlbumQuery photoAlbumQuery) {
        return baseMapper.selectListPage(page, photoAlbumQuery);
    }

    @Override
    public List<PhotoAlbumVo> selectList(PhotoAlbumQuery photoAlbumQuery) {
        return baseMapper.selectList(photoAlbumQuery);
    }

    @Override
    public int delBatch(int[] ids) {
        //先遍历图片库相册id，查到要删除的每个相册id所对应的图片list
        for (int i = 0; i < ids.length; i++) {
            PhotoGalleryQuery photoGalleryQuery = new PhotoGalleryQuery();
            photoGalleryQuery.setAlbumId((long) ids[i]);
            //图片list
            List<PhotoGalleryVo> list = photoGalleryMapper.selectList(photoGalleryQuery);
            //list不为空，则循环改动图片库相册id为0，相册id为0是默认相册
            if (list.size() > 0) {
                for (int j = 0; j < list.size(); j++) {
                    PhotoChgDto photoChgDto = new PhotoChgDto();
                    photoChgDto.setId(list.get(j).getId());
                    photoChgDto.setAlbumId(0L);
                    photoGalleryMapper.updatePhoto(photoChgDto);
                }
            }
        }
        //对图片处理过后删除相册
        return baseMapper.delBatch(ids);
    }

    @SneakyThrows
    @Override
    public void saveImportImg(MultipartFile file,int flag,Long parentId) {
        if(flag==0){

        String originalFilename = file.getOriginalFilename();
        String levelName = originalFilename.substring(0,6);
        String level2Name = originalFilename.substring(6,8);
        Long  bumId=0L;
        PhotoAlbum photoAlbum=null;
        try {
           photoAlbum=getOne(new QueryWrapper<PhotoAlbum>().eq("album_name",levelName).eq("album_level",1));
           if(null!=photoAlbum){
               PhotoAlbum    photoAlbum2=getOne(new QueryWrapper<PhotoAlbum>().eq("album_name",level2Name).eq("album_level",2).eq("parent_id",photoAlbum.getId()));
               if(null==photoAlbum2){
                   bumId=    insertLevle2(photoAlbum,level2Name);
               }else{
                   bumId=photoAlbum2.getId();
               }
           }
       if(null==photoAlbum){
           photoAlbum = new PhotoAlbum();
           photoAlbum.setIsEnable(WhetherEnum.YES.getValue());
           photoAlbum.setAlbumName(levelName);
           photoAlbum.setParentId(0L);
           photoAlbum.setAlbumLevel(1);
           baseMapper.insert(photoAlbum);
           PhotoAlbum    photoAlbum2=getOne(new QueryWrapper<PhotoAlbum>().eq("album_name",level2Name).eq("album_level",2).eq("parent_id",photoAlbum.getId()));
           if(null==photoAlbum2){
               bumId=    insertLevle2(photoAlbum,level2Name);
           }else{
               bumId=photoAlbum2.getId();
           }
       }
        }catch (Exception e) {
            throw  new Exception("文件上传失败！");
        }
        //文件上传
        uploadImg(file, bumId);

        }else{
            uploadImg(file, parentId);
        }
    }

    @Override
    public void improtExcel(MultipartFile file) {
        try{
         EasyExcel.read(file.getInputStream(), PhotoAlbumData.class, new PhotoAlbumDataListener(photoGalleryService,goodsService,goodsIntroService)).sheet().doRead();
        }catch (Exception e){

        }

    }

    @Override
    public List<PhotoAlbumVo> tree() {
        PhotoAlbumQuery photoAlbumQuery=new PhotoAlbumQuery();
        photoAlbumQuery.setLevel("1");
        photoAlbumQuery.setIsEnable(WhetherEnum.YES);
        List<PhotoAlbumVo>  list= baseMapper.selectList(photoAlbumQuery);
        for(PhotoAlbumVo vo:list){
            photoAlbumQuery.setLevel("2");
            photoAlbumQuery.setParentId(vo.getId());
            List<PhotoAlbumVo>  list2= baseMapper.selectList(photoAlbumQuery);
            vo.setChildList(list2);
        }
        return list;
    }

    @Override
    public List<PhotoAlbumVo> test() {
        return baseMapper.test();
    }

    private void uploadImg(MultipartFile file, Long bumId) {
        // 文件大小
        long size = file.getSize();

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 文件类型
        System.out.println(file.getName());
        String contentType = file.getContentType();
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            OssProperties oss = weiXingProperties.getAli().getOss();
            boolean upload = new AliOssUpload(oss).upload(oss.getBucket().getGoods(), originalFilename, file.getInputStream());
            PhotoGallery photoGallery=new PhotoGallery();
            photoGallery.setAlbumId(bumId);
            photoGallery.setIsEnable(WhetherEnum.YES.getValue());
            photoGallery.setPhotoAddr(originalFilename);
            photoGallery.setPhotoName(originalFilename);
            photoGalleryMapper.insert(photoGallery);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Long  insertLevle2(PhotoAlbum photoAlbum, String level2Name) {
        PhotoAlbum photoAlbum1 = new PhotoAlbum();
        photoAlbum1.setIsEnable(WhetherEnum.YES.getValue());
        photoAlbum1.setAlbumName(level2Name);
        photoAlbum1.setParentId(photoAlbum.getId());
        photoAlbum1.setAlbumLevel(2);
        baseMapper.insert(photoAlbum1);
        return  photoAlbum1.getId();
    }



}
